﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Platform.Model.Repositories;

namespace Platform.Model
{
	/// <summary>
	/// Lop quan ly danh sach mat hang
	/// </summary>
	public class ProductList
	{
		private List<Article> _articles;
		private Dictionary<string, Article> _mapper;

		/// <summary>
		/// Khoi tao doi tuong quan ly danh sach mat hang
		/// </summary>
		public ProductList()
		{
		}

		/// <summary>
		/// Tai danh sach mat hang vao bo nho
		/// </summary>
		/// <param name="lastRefresh">Thoi diem tai du lieu gan nhat</param>
		public void Refresh(DateTime? lastRefresh = null)
		{
			if (lastRefresh == null)
			{
				// Lay danh sach mat hang
				_articles = ArticleRepository.GetArticlesForMarket(WorkSession.Current.Market.ID);

				// Tao tu dien de anh xa giua Article No va ID
				_mapper = _articles.ToDictionary(x => x.ArtNo, x => x);
			}
			else
			{
				// Lay danh sach mat hang duoc cap nhat gan day nhat
				var newArts = ArticleRepository.GetLastModifiedArticles(WorkSession.Current.Market.ID, lastRefresh.Value);
				foreach (var prod in newArts)
				{
					// Neu mat hang da co trong danh sach cu thi xoa no
					// va thay the bang mat hang moi cap nhat
					if (_mapper.ContainsKey(prod.ArtNo))
					{
						_articles.Remove(_mapper[prod.ArtNo]);
						_mapper[prod.ArtNo] = prod;
					}
					else
						// Con neu chua co thi them vao danh sach
						_mapper.Add(prod.ArtNo, prod);
					_articles.Add(prod);
				}
			} // end if
		} // end method

        /// <summary>
        /// Thêm hoặc cập nhật mặt hàng
        /// </summary>
        /// <param name="art">Mặt hàng</param>
        /// <returns>Trả về mã mặt hàng Article.Id</returns>
	    public int AddOrUpdate(Article art)
	    {
			// Mat hang moi nhung co ma trung voi mat hang cu
			// khong them duoc => thong bao loi
			if (art.ID == 0 && _mapper.ContainsKey(art.ArtNo))
				throw new DuplicateNameException("Cannot add new article with duplicate ART_NO");
			
			// Them moi mat hang
			if (art.ID == 0)
			{
				art.Insert();
				//_articles.Add(art);
				_mapper.Add(art.ArtNo, art);
			}
			// truong hop cap nhat
			else
			{
				// Tim mat hang da co trong danh sach theo id
				var article = _articles.FirstOrDefault(x => x.ID == art.ID);
	
				// TRuong hop nhap ma moi nhung trung voi mat hang khac
				if (art.ArtNo != article.ArtNo && _mapper.ContainsKey(art.ArtNo))
					throw new DuplicateNameException("Cannot update article with duplicate ART_NO");

				art.Update();

				// Cap nhat gia tri moi cho mat hang
				article.ArtNo = art.ArtNo;
				article.ArtName = art.ArtName;
				article.Cat = art.Cat;
				article.Unit = art.Unit;
				article.LastUpdated = art.LastUpdated;

				// Xoa thong tin mat hang cu
				_mapper.Remove(article.ArtNo);

				// thay doi bang mat hang moi vua cap nhat
				_mapper.Add(art.ArtNo, art);
			}
			
            return art.ID;
	    }

        /// <summary>
        /// Xoá danh sách mặt hàng dựa trên danh sách Id được chọn
        /// </summary>
		/// <param name="art">Mat hang can xoa</param>
        /// <returns>Trả về kết quả True: đã xoá, False: lỗi</returns>
        public bool Delete(Article art)
        {
            try
            {
				Article.Objects.DeleteById(art.ID);
	            _mapper.Remove(art.ArtNo);
	            _articles.Remove(art);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

	    /// <summary>
		/// Lay mat hang theo ma so Article No
		/// </summary>
		/// <param name="artNo">Ma so cua mat hang</param>
		/// <returns>Tra ve mat hang co ma la ArtNo hoac null</returns>
		public Article GetArticle(string artNo)
		{
			return _mapper.ContainsKey(artNo) ? _mapper[artNo] : null;
		}

		/// <summary>
		/// Lay ID cua mat hang theo ma so Article No
		/// </summary>
		/// <param name="artNo">Ma so cua mat hang</param>
		/// <returns>Tra ve ID cua mat hang hoac bao loi neu khong tim thay</returns>
		public int GetArticleId(string artNo)
		{
			var article = GetArticle(artNo);
			if (article == null)
				throw new NullReferenceException("Khong tim thay mat hang co ma " + artNo);

			return article.ID;
		}

		/// <summary>
		/// Lay danh sach cac mat hang
		/// </summary>
		/// <returns>Danh sach tat ca cac mat hang</returns>
		public List<Article> ToList()
		{
			return _articles;
		}

        /// <summary>
        /// Sắp xếp mặt hàng tăng theo tên
        /// </summary>
        /// <returns>Trả về danh sách mặt hàng</returns>
        public  List<Article> SortByName()
        {
            return _articles.OrderBy(x=>x.ArtName).ToList();
        }
	}
}
